package cn.edu.nuc.android.oweibo.activities;

import java.text.SimpleDateFormat;
import java.util.Date;

import weibo4android.Status;
import weibo4android.Weibo;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.edu.nuc.android.oweibo.OWeiboApplication;
import cn.edu.nuc.android.oweibo.R;
import cn.edu.nuc.android.oweibo.tasks.PostPhotoAsyncTask;
import cn.edu.nuc.android.oweibo.tasks.PostPhotoAsyncTask.PostPhotoResponder;
import cn.edu.nuc.android.oweibo.tasks.PostWeiboAsyncTask;
import cn.edu.nuc.android.oweibo.tasks.PostWeiboAsyncTask.PostWeiboResponder;

public class PostActivity extends Activity implements PostWeiboResponder, PostPhotoResponder {

	private static final int REQUEST_CHOOSE_PHOTO_FROM_LIBRARY = 0;
	private static final int REQUEST_CHOOSE_PHOTO_FROM_CAMERA = 1;
	private OWeiboApplication app;
	private TextView counterText;
	private EditText weiboContent;
	private ProgressDialog progressDialog;
	private AlertDialog alertDialog;
	private Uri photoUri;
	private Button photoButton;
	private Weibo weibo;
	
	private OnClickListener libraryButtonClickListener = new DialogInterface.OnClickListener() {
		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			openPhotoLibrary();
		}
	};
	private OnClickListener cameraButtonClickListener = new DialogInterface.OnClickListener() {
		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			openCamera();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		app = (OWeiboApplication) getApplication();
		weibo = app.getWeibo();
		setContentView(R.layout.post_view);
		setUpViews();
	}

	/**
	 * 打开本地照相机
	 */
	protected void openCamera() {
		SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");
	    String filenameTimestamp = timeStampFormat.format(new Date());
	    ContentValues values = new ContentValues();
	    values.put(Media.TITLE, String.format("oweibo_photo_%s.jpg", filenameTimestamp));
	    values.put(Media.DESCRIPTION, getString(R.string.image_posted_from_o_weibo));
	    photoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

	    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
	    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
	    startActivityForResult(intent, REQUEST_CHOOSE_PHOTO_FROM_CAMERA);
	}

	/**
	 * 打开手机本地图片
	 */
	protected void openPhotoLibrary() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		startActivityForResult(intent, REQUEST_CHOOSE_PHOTO_FROM_LIBRARY);
	}
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (REQUEST_CHOOSE_PHOTO_FROM_LIBRARY == requestCode && RESULT_OK == resultCode) {
			photoToPostChosen(intent.getData());
		}else if(REQUEST_CHOOSE_PHOTO_FROM_CAMERA == requestCode && RESULT_OK == resultCode) {
			photoToPostChosen(photoUri);
		} else {
			super.onActivityResult(requestCode, resultCode, intent);
		}
	}

	
	/**
	 * 选择一个手机中的图片
	 * @param uri
	 */
	private void photoToPostChosen(Uri uri) {
		photoUri = uri;
		String id = photoUri.getLastPathSegment();
		if (null != id) {
			photoButton.setText(null);
			
			// 获取一个缩略图
			Bitmap thumbBitmap = MediaStore.Images.Thumbnails.getThumbnail(
					getContentResolver(), Long.parseLong(id),
					MediaStore.Images.Thumbnails.MICRO_KIND, null);
			photoButton.setBackgroundDrawable(new BitmapDrawable(thumbBitmap));
		}
	}

	// called when post button on view is clicked
	public void postButtonClicked(View view) {
		postValidWeiboOrWarn();
	}

	// called when post button on view is clicked
	public void photoButtonClicked(View view) {
		new AlertDialog.Builder(this)
				.setTitle(R.string.attach_photo)
				.setMessage(R.string.choose_a_photo_source)
				.setNeutralButton(R.string.photo_library, libraryButtonClickListener)
				.setPositiveButton(R.string.camera,
						cameraButtonClickListener  )
				.setNegativeButton(android.R.string.cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						}).show();
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return MenuHelper.openActivityFromMenuItem(this, item);
	}

	/**
	 * 产生menu项
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	/**
	 * 发表微博或者发表错误的一些提醒
	 */
	private void postValidWeiboOrWarn() {
		String postText = weiboContent.getText().toString();
		int postLength = postText.length();
		if (140 < postLength) {
			alertDialog = new AlertDialog.Builder(this)
					.setTitle(R.string.too_many_characters)
					.setMessage(R.string.too_many_characters_description)
					.setPositiveButton(android.R.string.ok,
							new OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
									alertDialog = null;
								}
							}).show();
		} else if (0 == postLength) {
			alertDialog = new AlertDialog.Builder(this)
			.setTitle(R.string.weibo_is_blank)
			.setMessage(R.string.blank_weibo_description)
			.setPositiveButton(android.R.string.ok,
					new OnClickListener() {
						public void onClick(DialogInterface dialog,
								int which) {
							alertDialog.dismiss();
							alertDialog = null;
						}
					}).show();
		} else {
			if (null == photoUri) {
				new PostWeiboAsyncTask(this, app.getWeibo()).execute(postText); // 发表不带图片的文本内容
			} else {
				new PostPhotoAsyncTask(this, weibo, this).execute(postText, photoUri); // 发表带图片的微博内容
			}
		}
	}

	@Override
	public void weiboPosting() {
		progressDialog = ProgressDialog.show(this,
				getResources().getString(R.string.posting_title),
				getResources().getString(R.string.posting_description));
	}

	/**
	 * 微博发送完毕，并通过Toast显示提醒发送成功！
	 */
	@Override
	public void weiboPosted(Status status) {
		progressDialog.dismiss();
		Toast.makeText(this, R.string.weibo_posted, Toast.LENGTH_LONG).show();
		finish();
	}

	private void setUpViews() {
		counterText = (TextView) findViewById(R.id.counter_text);
		weiboContent = (EditText) findViewById(R.id.weibo_contents);
		photoButton = (Button)findViewById(R.id.photo_button);
		configurePhotoButton();
		weiboContent.addTextChangedListener(new TextWatcher() {

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				int charLeft = 140 - s.length();
				counterText.setText(String.valueOf(charLeft));
			}

			@Override
			public void afterTextChanged(Editable s) {
			}

		});
	}

	private void configurePhotoButton() {
		if (null == photoUri) {
			photoButton.setText(R.string.attach_photo);
		} else {
			photoButton.setText(null);
		}
	}

	@Override
	public void photoPosting() {
		weiboPosting();
	}

	@Override
	public void photoPosted(Status status) {
		weiboPosted(status);
	}

}
